package cms.simmytech.dialect;

import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.util.StringUtils;
import org.thymeleaf.IEngineConfiguration;
import org.thymeleaf.context.ITemplateContext;
import org.thymeleaf.model.IModel;
import org.thymeleaf.model.IModelFactory;
import org.thymeleaf.model.IProcessableElementTag;
import org.thymeleaf.processor.element.AbstractElementTagProcessor;
import org.thymeleaf.processor.element.IElementTagStructureHandler;
import org.thymeleaf.standard.expression.IStandardExpression;
import org.thymeleaf.standard.expression.IStandardExpressionParser;
import org.thymeleaf.standard.expression.StandardExpressions;
import org.thymeleaf.templatemode.TemplateMode;

public class TimeCustomDialect extends AbstractElementTagProcessor {

	Log log = LogFactory.getLog(RoleCustomDialect.class);

	private static final String TAG_NAME = "time";
	private static final int PRECEDENCE = 1000;


	public TimeCustomDialect(final String dialectPrefix) {
		super(TemplateMode.HTML, // 此处理器将仅应用于HTML模式
				dialectPrefix, // 要应用于名称的匹配前缀
				TAG_NAME, // 标签名称：匹配此名称的特定标签
				true, // 没有应用于标签名的前缀
				null, // 无属性名称：将通过标签名称匹配
				false, // 没有要应用于属性名称的前缀
				PRECEDENCE// 优先(内部方言自己的优先
		);
	}

	@Override
	protected void doProcess(ITemplateContext context, IProcessableElementTag tag,
			IElementTagStructureHandler structureHandler) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String timeInt = tag.getAttributeValue("timeInt");
		String ff=tag.getAttributeValue("ff");
		if (!StringUtils.isEmpty(timeInt)) {
			if(!StringUtils.isEmpty(ff)){
				ff=getExpressionValue(context,ff).toString();
				sdf.applyPattern(ff);
			}
			timeInt=getExpressionValue(context, timeInt).toString();
			String timeStr =timeInt.equals("0")?"--":sdf.format(new Date(Long.parseLong(timeInt)*1000));
			IModelFactory modelFactory = context.getModelFactory();
			IModel model = modelFactory.createModel();
			model.add(modelFactory.createText(timeStr));
			structureHandler.replaceWith(model, false);

		}
	}
	private Object getExpressionValue(ITemplateContext iTemplateContext, String expressionString) {
	    final IEngineConfiguration configuration = iTemplateContext.getConfiguration();
	    final IStandardExpressionParser parser = StandardExpressions.getExpressionParser(configuration);
	    // 解析expression
	    final IStandardExpression expression = parser.parseExpression(iTemplateContext, expressionString);
	    // 获取expression的执行结果
	    return expression.execute(iTemplateContext);
	}
}
